package com.leyou.sms.utils;

import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.leyou.common.exception.pojo.ExceptionEnum;
import com.leyou.common.exception.pojo.LyException;
import com.leyou.common.utils.JsonUtils;
import com.leyou.sms.config.SmsConstants;
import com.leyou.sms.config.SmsProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

@Slf4j
@Component
public class SmsHelper {

    @Autowired
    private SmsProperties smsProp;

    @Autowired
    private IAcsClient client;


    public void sendCode(String phone, String code){
        log.info("【阿里云短信工具类】开始调用!");
        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain(smsProp.getDomain());
        request.setSysVersion(smsProp.getVersion());
        request.setSysAction(smsProp.getAction());
        request.putQueryParameter(SmsConstants.SMS_PARAM_REGION_ID, smsProp.getRegionID());
        request.putQueryParameter(SmsConstants.SMS_PARAM_KEY_PHONE, phone);
        request.putQueryParameter(SmsConstants.SMS_PARAM_KEY_SIGN_NAME, smsProp.getSignName());
        request.putQueryParameter(SmsConstants.SMS_PARAM_KEY_TEMPLATE_CODE, smsProp.getVerifyCodeTemplate());
        request.putQueryParameter(SmsConstants.SMS_PARAM_KEY_TEMPLATE_PARAM, "{\""+smsProp.getCode()+"\":\""+code+"\"}");
        try {
            CommonResponse response = client.getCommonResponse(request);
            //将发短信的返回结果转成Map
            Map<String, String> respMap = JsonUtils.toMap(response.getData(), String.class, String.class);
            if(respMap.get(SmsConstants.SMS_RESPONSE_KEY_CODE).equals(SmsConstants.OK)){
                log.info("【阿里云短信工具类】发送短信成功!手机用户{}已经获取到了验证码。", phone);
            }else {
                log.error("【阿里云短信工具类】发送短信失败!失败原因为：{}", respMap.get(SmsConstants.SMS_RESPONSE_KEY_MESSAGE));
            }
        } catch (ServerException e) {
            log.error("【阿里云短信工具类】阿里云服务器异常!失败原因为：{}", e.getMessage());
            throw new LyException(ExceptionEnum.SEND_MESSAGE_ERROR);
        } catch (ClientException e) {
            log.error("【阿里云短信工具类】乐优服务器异常!失败原因为：{}", e.getMessage());
            throw new LyException(ExceptionEnum.SEND_MESSAGE_ERROR);
        }
    }

}
